package com.dragon.mmochat.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.dragon.mmochat.model.role.MmochatGm;

public class MmochatGmDao extends SimpleJdbcDaoSupport {
	private static final GmRowMapper gmMapper = new GmRowMapper();

	// 获取所有GM
	private static final String getAllGmSql = "select * from gm";

	public List<MmochatGm> getAllGm() {
		return getSimpleJdbcTemplate().query(getAllGmSql, gmMapper);
	}

	// 获取GM信息
	private static final String getGmByNameSql = "select * from gm where username = ?";

	public MmochatGm getGmByName(String name) {
		return getSimpleJdbcTemplate().queryForObject(getGmByNameSql, gmMapper,
				name);
	}

	// 创建GM ID
	private static final String createNewGmIdSql = "select nextval('gm_id_seq'::regclass)";

	public int createNewGmId() {
		return getSimpleJdbcTemplate().queryForInt(createNewGmIdSql);
	}

	// 创建GM
	private static final String addGmSql = "insert into gm(id, username, password, priority, truename) "
			+ "values(?, ?, ?, ?, ?)";

	public void addGm(int id, String username, String password, int priority,
			String truename) {
		getSimpleJdbcTemplate().update(addGmSql, id, username, password,
				priority, truename);
	}

	// 删除GM
	private static final String delGmSql = "delete from gm where username = ?";

	public void delGm(String username) {
		getSimpleJdbcTemplate().update(delGmSql, username);
	}

	// 修改GM信息
	private static final String editGmSql = "update gm set truename = ?, priority = ? "
			+ "where username = ?";

	public void editGm(String truename, int priority, String username) {
		getSimpleJdbcTemplate().update(editGmSql, truename, priority, username);
	}
	
	// 修改GM密码
	private static final String editGmPwdSql = "update gm set password = ? "
			+ "where username = ?";

	public void editGmPwd(String pwd, String username) {
		getSimpleJdbcTemplate().update(editGmPwdSql, pwd, username);
	}

	static class GmRowMapper implements ParameterizedRowMapper<MmochatGm> {
		@Override
		public MmochatGm mapRow(ResultSet rs, int rowNum) throws SQLException {
			MmochatGm gm = new MmochatGm();
			gm.setId(rs.getInt("id"));
			gm.setUsername(rs.getString("username"));
			gm.setPassword(rs.getString("password"));
			gm.setPriority(rs.getInt("priority"));
			gm.setTruename(rs.getString("truename"));
			return gm;
		}
	}
}
